package config

import (
	"flag"
	"fmt"
	"os"
	"time"
)

var (
	Version   = "0.1.0"
	BuildDate = "unknown"
	GitCommit = "unknown"
)

// Config 包含所有配置参数
type Config struct {
	ListenAddr     string
	MetricsPath    string
	ScrapeTimeout  time.Duration
	ScrapeInterval time.Duration
	TopProcesses   int
	LogLevel       string
	LogPath        string
	ShowVersion    bool
	Pprof          bool
	Pprofaddr      string
}

// ParseFlags 解析命令行参数并返回配置结构体
func ParseFlags() *Config {
	var cfg Config

	flag.StringVar(&cfg.ListenAddr, "web.listen-address", ":8083", "Address to listen on for web interface and telemetry")
	flag.StringVar(&cfg.MetricsPath, "web.telemetry-path", "/metrics", "Path under which to expose metrics")
	flag.DurationVar(&cfg.ScrapeTimeout, "scrape.timeout", 10*time.Second, "Timeout for trying to get top metrics")
	flag.DurationVar(&cfg.ScrapeInterval, "scrape.interval", 30*time.Second, "Interval between scrapes")
	flag.IntVar(&cfg.TopProcesses, "top.processes", 10, "Number of top processes to monitor")
	flag.StringVar(&cfg.LogLevel, "log.level", "info", "Log level (debug, info, warn, error)")
	flag.StringVar(&cfg.LogPath, "log.path", "/tmp/log", "Log path")
	flag.BoolVar(&cfg.ShowVersion, "version", false, "Show version information")
	flag.BoolVar(&cfg.Pprof, "pprof", false, "Run pprof")
	flag.StringVar(&cfg.Pprofaddr, "pprofAddr", ":8084", "Address to listen on for  pprof ")

	// 自定义帮助信息
	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0])
		fmt.Fprintf(os.Stderr, "A Prometheus exporter for top command metrics\n\n")
		flag.PrintDefaults()
		//fmt.Fprintf(os.Stderr, "\nEnvironment variables:\n")
		//fmt.Fprintf(os.Stderr, "  TOP_EXPORTER_LISTEN_ADDR    equivalent to -web.listen-address\n")
		//fmt.Fprintf(os.Stderr, "  TOP_EXPORTER_INTERVAL      equivalent to -scrape.interval\n")
	}

	flag.Parse()

	//if envAddr := os.Getenv("TOP_EXPORTER_LISTEN_ADDR"); envAddr != "" {
	//	cfg.ListenAddr = envAddr
	//}

	return &cfg
}
